<?php

declare(strict_types=1);

namespace App\CustHub\Service;

use App\CustHub\Mapper\ChCorpMapper;
use App\CustHub\Mapper\ChListenRoomLogMapper;
use App\CustHub\Mapper\ChListenRoomMapper;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Mapper\ChRoomMapper;
use App\CustHub\Model\ChCorp;
use App\Robot\Service\RobotApiService;
use FriendsOfHyperf\Lock\Exception\LockTimeoutException;
use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Model;
use Hyperf\Di\Annotation\Inject;
use Mine\Abstracts\AbstractService;
use Mine\Exception\NormalStatusException;
use Mine\MineModel;
use function FriendsOfHyperf\Lock\lock;
use function Hyperf\Collection\data_get;
use function Hyperf\Support\optional;

class ChListenRoomService extends AbstractService
{
    public $mapper;

    protected $limit_listen_room_total=100;

    #[Inject]
    public  ChRoomMapper $roomMapper;

    #[Inject]
    public  ChRobotMapper $robotMapper;



    #[Inject]
    public  ChListenRoomLogMapper $roomListenLogMapper;

    #[Inject]
    protected ChConfigService $configService;

    public function __construct(ChListenRoomMapper $mapper)
    {
        $this->mapper = $mapper;
    }


    public function getListenRoomByDay($params)
    {
        $contactBuild = $this->roomMapper->model::query()->where('main_uid',$params['main_uid']);
        $paginate=$contactBuild->selectRaw(
            "FROM_UNIXTIME(create_time, '%Y-%m-%d') as date,
            count(*) as room_total,
            count(*) as in_room_total,
            count(*) as out_room_total,
            count(*) as speek_people_total,
            count(*) as speek_total"
        )   ->groupBy("date")
            ->orderBy("date",'desc')
            ->paginate((int)$params['page_size']);
        return $this->roomMapper->setPaginate($paginate);
    }

    public function getListenRoomList($params)
    {
        $range=data_get($params,'range');
        $time=data_get($params,'time','last_7_days');
        if(!empty($data)){
            return $data;
        }
        if($time){
            $range=$this->getDataRange($time);
        }
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;
        $start=strtotime($range[0]);
        $end=strtotime($range[1]);
        $list = $this->mapper->model::query()->with(['user'=>function ($query) {
            $query->select('id','nickname');
        },'room'=>function ($query) {
            $query->select('id','room_name');
        },'robot'=>function ($query) {
            $query->select('id','nickname');
        }])->leftJoin('ch_listen_room_behavior','ch_listen_room_behavior.room_id','=','ch_listen_room.room_id')->selectRaw("
          ch_listen_room.*,
          SUM(CASE WHEN ch_listen_room_behavior.created_at between '{$range[0]}' and '{$range[1]}' and ch_listen_room_behavior.behavior_type = 1 then 1 else 0 end) as in_room_total,
          SUM(CASE WHEN ch_listen_room_behavior.created_at between '{$range[0]}' and '{$range[1]}' and ch_listen_room_behavior.behavior_type = 2 then 1 else 0 end) as out_room_total,
          SUM(CASE WHEN ch_listen_room_behavior.created_at between '{$range[0]}' and '{$range[1]}' and ch_listen_room_behavior.behavior_type = 3 then ch_listen_room_behavior.times else 0 end) as speek_total,
          COUNT(DISTINCT CASE WHEN ch_listen_room_behavior.created_at between '{$range[0]}' and '{$range[1]}' and ch_listen_room_behavior.behavior_type = 3 then ch_listen_room_behavior.user_id else null end) as speek_people_total
        ")
            ->where('ch_listen_room.main_uid',$params['main_uid'])
            ->groupBy('ch_listen_room.room_id') // 添加这行以防重复
            ->paginate((int)$pageSize);
        $list->getCollection()->transform(function ($item) {
            $item->liveness=$item->member_total>0?bcdiv((string)($item->speek_people_total*100),(string)$item->member_total,2):0;
            return $item;
        });
        $data=$this->mapper->setPaginate($list);
        $data['limit_listen_room_total']=$this->limit_listen_room_total;
        $data['listen_room_total']= $this->mapper->handleSearch($this->mapper->getModel()->query(),$params)->count();
        $data['surplus_listen_room_total']= $data['limit_listen_room_total']-$data['listen_room_total'];
        return $data;
    }


    public function getConfig($params)
    {
        return $this->configService->getConfigByGroupKey($params['uid'],$params['main_uid'],'listen_room');
    }
    public function getListenRoomLogList($params)
    {
        $pageSize = $params['page_size'] ?? MineModel::PAGE_SIZE;

        $list = $this->roomListenLogMapper->handleSearch($this->roomListenLogMapper->getModel()->query()->with(['user'=>function ($query) {
            $query->select('id','nickname');
        }]),$params);
        return $this->roomListenLogMapper->setPaginate($list->paginate((int)$pageSize));
    }
    public function deleteListen($params)
    {
        $ids = explode(",",$params['ids']);
        $result = $this->roomListenLogMapper->delete($ids);
        if($result){
            $this->roomListenLogMapper->save([
                'main_uid'=>$params['main_uid'],
                'uid'=>$params['uid'],
                'room_id'=>$params['ids'],
                'b_type'=>2
            ]);
            return true;
        }

        return false;
    }

    public function addListenRoom($params)
    {
        $roomIds=explode(',',$params['room_ids']);
        foreach ($roomIds as $roomId){
            $listenRoom=$this->mapper->getModel()->query()->where([
                'main_uid'=>$params['main_uid'],
                'uid'=>$params['uid'],
                'room_id'=>$roomId,
            ])->first();
            if (empty($listenRoom)){
                $roomInfo=$this->roomMapper->findById($roomId);
                $robotInfo=$this->robotMapper->findByUserId($roomInfo['create_user_id'],$roomInfo['main_uid']);
                $this->mapper->getModel()->query()->create([
                    'main_uid'=>$params['main_uid'],
                    'uid'=>$params['uid'],
                    'room_id'=>$roomId,
                    'member_total'=>$roomInfo['room_member_count'],
                    'robot_id'=>!empty($robotInfo['id'])?$robotInfo['id']:0
                ]);

            }
        }
        $this->roomListenLogMapper->save([
            'main_uid'=>$params['main_uid'],
            'uid'=>$params['uid'],
            'room_id'=>$params['room_ids'],
            'b_type'=>1
        ]);
        return true;
    }


    protected function getDataRange(string $time)
    {
        $data = match ($time) {
            'today' => [date('Y-m-d 00:00:00'), date('Y-m-d 23:59:59')],
            'yesterday' => [date('Y-m-d 00:00:00', strtotime('-1 day')), date('Y-m-d 23:59:59', strtotime('-1 day'))],
            'last_7_days' => [date('Y-m-d H:i:s', strtotime('-7 days')), date('Y-m-d 23:59:59')],
            'last_15_days' => [date('Y-m-d H:i:s', strtotime('-15days')),date('Y-m-d 23:59:59')],
            'last_30_days' => [date('Y-m-d H:i:s', strtotime('-30 days')),date('Y-m-d 23:59:59')],
            default => []
        };
        return $data;
    }

}